package com.zhuchang.self_rpc.test.democoding.nettydemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author RenPu
 * @Date 2022/2/10 12:16
 * @Version 1.0
 * @Description: Netty实现群聊系统---服务端
 **/
public class NettyGroupChatServer {

    //端口属性
    private int port;

    public NettyGroupChatServer(int port) {
        this.port = port;
    }

    //
    public void startServer() throws InterruptedException {
    //创建channel监听线程组
    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    //创建具体业务的处理，数据返回的线程组
    NioEventLoopGroup workGroup =new  NioEventLoopGroup();
  try{
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup,workGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG,128)
            .childOption(ChannelOption.SO_KEEPALIVE,true)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("decoder",new StringDecoder())
                            .addLast("encoder",new StringEncoder())
                            .addLast(new GroupChatServerHandle());


                }
            });

      System.out.println("netty，服务已经开启........");
      ChannelFuture future  = serverBootstrap.bind(port).sync();
     future.channel().closeFuture().sync();
     }  finally {
          bossGroup.shutdownGracefully();
          workGroup.shutdownGracefully();
      }

    }


    public static void main(String[] args) {
        NettyGroupChatServer nettyGroupChatServer = new NettyGroupChatServer(7886);
        try {
            nettyGroupChatServer.startServer();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }


}
